package cn.xiongxf.mq.consumer;

import cn.xiongxf.constant.MQConstant;
import cn.xiongxf.dto.MessageStationDto;
import cn.xiongxf.service.IMessageStationService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 站内消息消费者
 */
@Component
@RocketMQMessageListener(
        consumerGroup = "service-common-consumer-message-station",
        topic = MQConstant.TOPIC_MESSAGE_STATION,
        selectorExpression = MQConstant.TAGS_MESSAGE_STATION )
@Slf4j
public class MessageStationConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageStationService messageStationService;

    @Override
    public void onMessage(MessageExt message) {
        if(message.getBody() == null || message.getBody().length == 0) return;
        // 获取消息对象
        String json = new String(message.getBody(), StandardCharsets.UTF_8);
        MessageStationDto messageStationDto = JSON.parseObject(json, MessageStationDto.class);
        // 保存站内消息到DB
        messageStationService.saveMessageStation(messageStationDto);
        log.info("站内消息保存成功：{}" , messageStationDto);
    }
}
